package cn.springcloud.fix.common.core.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class CookieUtil {

    public static void addCookie(HttpServletResponse response, String domain, String cookieName, String cookieValue, int maxAge) throws Exception {
        Cookie cookie = new Cookie(cookieName, URLEncoder.encode(cookieValue, "utf-8"));
        cookie.setDomain(domain);
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 根据cookieName获取Cookie
     */
    public static Cookie getCookieByCookieName(String cookieName, HttpServletRequest request) {
        Map<String, Cookie> cookieMap = readCookieMap(request);
        if (cookieMap == null || cookieMap.size() == 0) {
            return null;
        }
        return cookieMap.get(cookieName);
    }

    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if (cookies == null) return cookieMap;
        for (Cookie cookie : cookies) {
            cookieMap.put(cookie.getName(), cookie);
        }
        return cookieMap;
    }

    //延长cookie的有效时间，默认延长1小时
    // public static void proLongCookieTime(HttpServletResponse response, String domain, Cookie cookie) {
    //     String cookVal = cookie.getValue();
    //     String name = cookie.getName();
    //     Cookie cookies = new Cookie(name, cookVal);
    //     cookies.setDomain(DOMAIN);
    //     cookies.setPath("/");
    //     cookies.setHttpOnly(false);
    //     cookies.setMaxAge(60 * 60);
    //     response.addCookie(cookies);
    // }

    public static void deleteCookie(Cookie cookie, String domain, HttpServletResponse response) {
        if (cookie == null) return;
        cookie.setValue(null);
        cookie.setDomain(domain);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
